package org.jeecg.modules.demo.storeinfo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basestaffstatus.service.IBaseStaffStatusService;
import org.jeecg.modules.demo.stockmanage.entity.StockManage;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.util.HttpUtils;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺信息
 * 2022-01-20
 */
@Api(tags = "店铺信息")
@RestController
@RequestMapping("/storeinfo/storeInfo")
@Slf4j
public class StoreInfoController extends JeecgController<StoreInfo, IStoreInfoService> {

    @Autowired
    private IStoreInfoService storeInfoService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBaseStaffStatusService baseStaffStatusService;

    @Autowired
    private RedisUtils redisUtils;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "店铺信息-分页列表查询")
    @ApiOperation(value = "店铺信息-分页列表查询", notes = "店铺信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StoreInfo storeInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<StoreInfo> queryWrapper = new QueryWrapper<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        SysRole role = sysRoleService.getRoleByUserId(userId);
        if (role == null) {
            return Result.error("当前登录用户未绑定角色");
        }
        if (!"管理员".equals(role.getRoleType())) {
            queryWrapper.eq("boss_id", sysUser.getId());
        }
        StoreInfo storeInfo2 = new StoreInfo();
        storeInfo2.setStoreName(storeInfo.getStoreName());
        storeInfo2.setBossName(storeInfo.getBossName());
        Map<String, Object> map = org.jeecg.modules.util.BeanUtils.bean2Map(storeInfo2);
        map.remove("prebookHours");
        storeInfo2 = org.jeecg.modules.util.BeanUtils.map2Bean(map, StoreInfo.class);
//        req.getp
        QueryGenerator.initQueryWrapper(queryWrapper, storeInfo2, req.getParameterMap());

        Page<StoreInfo> page = new Page<>(pageNo, pageSize);
        IPage<StoreInfo> pageList = storeInfoService.page(page, queryWrapper);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
        // 为了保持返回值不变，沿用框架的分页方式。分页查询后用每项的商品id查商品详情
        List<StoreInfo> records = pageList.getRecords();
        List<Map<String, Object>> records1 = records.stream().map(si -> {
            Map<String, Object> m = ToolsUtils.objectToMap(si);
            SysUser user = sysUserService.getById(si.getBossId());
            if (user != null) {
                m.put("bossUsername", user.getUsername());
            }
            Date createTime = (Date) m.get("createTime");
            Date updateTime = (Date) m.get("updateTime");
            Date storeExpiryDate = (Date) m.get("storeExpiryDate");
            if (createTime != null) {
                m.put("createTime", sdf.format(createTime));
            }
            if (updateTime != null) {
                m.put("updateTime", sdf.format(updateTime));
            }
            if (storeExpiryDate != null) {
                m.put("storeExpiryDate", sdf.format(storeExpiryDate));
            }
            Date businessStart = (Date) m.get("businessStart");
            Date businessEnd = (Date) m.get("businessEnd");
            if (businessStart != null) {
                m.put("businessStart", sdf2.format(businessStart));
            }
            if (businessEnd != null) {
                m.put("businessEnd", sdf2.format(businessEnd));
            }
            return m;
        }).collect(Collectors.toList());
        IPage<Map<String, Object>> pageList1 = new PageDTO<>();
        BeanUtils.copyProperties(pageList, pageList1);
        pageList1.setRecords(records1);
        return Result.OK(pageList1);
    }

    @AutoLog(value = "店铺信息-根据登录账号获取店铺信息")
    @ApiOperation(value = "店铺信息-根据登录账号获取店铺信息", notes = "店铺信息-根据登录账号获取店铺信息")
    @GetMapping(value = "/getStoreInfo")
    public Result<?> getStoreInfo(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        StoreInfo storeInfo = storeInfoService.getById(storeId);
        return Result.OK(storeInfo);
    }

    /**
     * 添加 店铺账号字段 匹配到 每个user storename 字段中
     */
    @AutoLog(value = "店铺信息-添加")
    @ApiOperation(value = "店铺信息-添加", notes = "店铺信息-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> add(@RequestBody StoreInfo storeInfo) {
        //平台管理员 才有权限添加店铺 并 自动生成 店铺管理员账号
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        SysRole role = sysRoleService.getRoleByUserId(userId);
        if (role == null) {
            return Result.error("当前登录用户未绑定角色");
        }
        if (!"管理员".equals(role.getRoleType())) {
            return Result.error("无添加权限");
        }
        if (oConvertUtils.isEmpty(storeInfo.getBossId())) {
            return Result.error("请选择老板账号");
        }
        storeInfo.setXcxAppId(null);
        storeInfo.setXcxAppSecret(null);
        storeInfo.setGzhAppId(null);
        storeInfo.setGzhAppSecret(null);
        storeInfo.setGzhStoreName(null);
        storeInfo.setGzhToken(null);
        storeInfo.setGzhAesKey(null);
        storeInfo.setSaobeiMerchantNo(null);
        storeInfo.setSaobeiAccessToken(null);
        storeInfo.setSaobeiTerminalId(null);
        storeInfoService.save(storeInfo);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     */
    @AutoLog(value = "店铺信息-编辑")
    @ApiOperation(value = "店铺信息-编辑", notes = "店铺信息-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> edit(@RequestBody StoreInfo storeInfo) {
        // 不修改bossId和过期时间
        storeInfo.setBossId(null);
//        storeInfo.setStoreExpiryDate(null);
        storeInfo.setXcxAppId(null);
        storeInfo.setXcxAppSecret(null);
        storeInfo.setGzhAppId(null);
        storeInfo.setGzhAppSecret(null);
        storeInfo.setGzhStoreName(null);
        storeInfo.setGzhToken(null);
        storeInfo.setGzhAesKey(null);
        storeInfo.setSaobeiMerchantNo(null);
        storeInfo.setSaobeiAccessToken(null);
        storeInfo.setSaobeiTerminalId(null);

        storeInfoService.updateById(storeInfo);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "店铺信息-通过id删除")
    @ApiOperation(value = "店铺信息-通过id删除", notes = "店铺信息-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!"管理员".equals(sysUser.getRoleType())) {
            return Result.error("仅管理员可删除店铺");
        }
        storeInfoService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "店铺信息-批量删除")
    @ApiOperation(value = "店铺信息-批量删除", notes = "店铺信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        //this.storeInfoService.removeByIds(Arrays.asList(ids.split(",")));
        //return Result.OK("批量删除成功!");
        return Result.error("平台暂不支持批量删除");
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "店铺信息-通过id查询")
    @ApiOperation(value = "店铺信息-通过id查询", notes = "店铺信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StoreInfo storeInfo = storeInfoService.getById(id);
        if (storeInfo == null) {
            return Result.error("未找到对应数据");
        }
        String strStoreBanner = storeInfo.getStoreBanner();
        List<String> listStoreBanner = Arrays.asList(strStoreBanner.split(","));
        for (int i = 0; i < listStoreBanner.size(); i++) {
            listStoreBanner.set(i, "https://www.kyz66.com/fubaihui/sys/common/static/" + listStoreBanner.get(i));
        }
        String strStoreBanner2 = Joiner.on(",").join(listStoreBanner);
        storeInfo.setStoreBanner(strStoreBanner2);

        String strStorePhoto = storeInfo.getStorePhoto();
        List<String> listStorePhoto = Arrays.asList(strStorePhoto.split(","));
        for (int i = 0; i < listStorePhoto.size(); i++) {
            listStorePhoto.set(i, "https://www.kyz66.com/fubaihui/sys/common/static/" + listStorePhoto.get(i));
        }
        String strStorePhoto2 = Joiner.on(",").join(listStorePhoto);
        storeInfo.setStorePhoto(strStorePhoto2);

        storeInfo.setStoreVideo("https://www.kyz66.com/fubaihui/sys/common/static/" + storeInfo.getStoreVideo());

        return Result.OK(storeInfo);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StoreInfo storeInfo) {
        //return super.exportXls(request, storeInfo, StoreInfo.class, "店铺信息");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<StoreInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, storeInfo, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<StoreInfo> pageList = storeInfoService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "店铺列表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, StockManage.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("店铺列表数据", "导出人:" + user.getRealname(), "店铺列表");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StoreInfo.class);
    }

    /**
     * 配置公众号、小程序、扫呗
     */
    @PutMapping(value = "/config")
    public Result<?> config(@RequestBody StoreInfo storeInfo) {

        StoreInfo storeInfo1 = new StoreInfo();
        storeInfo1.setId(storeInfo.getId());
        storeInfo1.setXcxAppId(storeInfo.getXcxAppId());
        storeInfo1.setXcxAppSecret(storeInfo.getXcxAppSecret());
        storeInfo1.setGzhAppId(storeInfo.getGzhAppId());
        storeInfo1.setGzhAppSecret(storeInfo.getGzhAppSecret());
        storeInfo1.setGzhStoreName(storeInfo.getGzhStoreName());
        storeInfo1.setGzhToken(storeInfo.getGzhToken());
        storeInfo1.setGzhAesKey(storeInfo.getGzhAesKey());
        storeInfo1.setSaobeiMerchantNo(storeInfo.getSaobeiMerchantNo());
        storeInfo1.setSaobeiAccessToken(storeInfo.getSaobeiAccessToken());
        storeInfo1.setSaobeiTerminalId(storeInfo.getSaobeiTerminalId());
        storeInfo1.setGzUrl(storeInfo.getGzUrl());
        storeInfoService.updateById(storeInfo1);
        return Result.OK("配置成功!");
    }

    /**
     * 设置公众号菜单
     */
    @GetMapping(value = "/configGzhMenu")
    public Result<?> configGzhMenu(@RequestParam("id") String id, @RequestParam("menu") String menu) {

        StoreInfo store = storeInfoService.getById(id);
        if (store == null) {
            return Result.error("店铺不存在");
        }
        String gzhAppId = store.getGzhAppId();
        String gzhAppSecret = store.getGzhAppSecret();
        if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
            return Result.error("店铺还未绑定公众号，请先保存公众号appId和appSecret");
        }
        String xcxAppId = store.getXcxAppId();
        if (StringUtils.isEmpty(xcxAppId)) {
            return Result.error("店铺还未绑定小程序，请先保存小程序appId");
        }

        String body = "{\n" +
                "\t\"button\": [";

        List<Map> listMenu = (List<Map>) JSON.parse(menu);
        for (int index = 0; index < listMenu.size(); index++) {
            if (index < listMenu.size() - 1) {
                if (!((listMenu.get(index).get("name")).toString().startsWith("菜单"))) {
                    body = body + "{\n" +
                            "\t\t\"type\": \"miniprogram\",\n" +
                            "\t\t\"name\": \"" + listMenu.get(index).get("name") + "\",\n" +
                            "\t\t\"url\": \"http://mp.weixin.qq.com\",\n" +
                            "\t\t\"appid\": \"" + xcxAppId + "\",\n" +
                            "\t\t\"pagepath\": \"" + listMenu.get(index).get("pagepath") + "\"\n" +
                            "\t},";
                }

            } else if (index == listMenu.size() - 1) {
                if (!((listMenu.get(index).get("name")).toString().startsWith("菜单"))) {
                    body = body + "{\n" +
                            "\t\t\"type\": \"miniprogram\",\n" +
                            "\t\t\"name\": \"" + listMenu.get(index).get("name") + "\",\n" +
                            "\t\t\"url\": \"http://mp.weixin.qq.com\",\n" +
                            "\t\t\"appid\": \"" + xcxAppId + "\",\n" +
                            "\t\t\"pagepath\": \"" + listMenu.get(index).get("pagepath") + "\"\n" +
                            "\t}]\n" +
                            "}";
                } else {
                    body = body.substring(0, body.length() - 1);
                    body = body + "\t]\n" +
                            "}";
                }

            }

        }

        try {
            String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
            String result1 = HttpUtils.sendGet(url1);
            JSONObject resultJson1 = JSON.parseObject(result1);
            String errcode = resultJson1.getString("errcode");
            if (errcode != null && !"0".equals(errcode)) {
                log.debug("获取accessToken返回值异常，错误码：{}", errcode);
                return Result.error("获取accessToken返回值异常，错误码：" + errcode + "result：" + resultJson1);
            }
            String accessToken = resultJson1.getString("access_token");

            String url2 = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;

            String body2 = "{\n" +
                    "\t\"button\": [{\n" +
                    "\t\t\"type\": \"miniprogram\",\n" +
                    "\t\t\"name\": \"线上商城\",\n" +
                    "\t\t\"url\": \"http://mp.weixin.qq.com\",\n" +
                    "\t\t\"appid\": \"" + xcxAppId + "\",\n" +
                    "\t\t\"pagepath\": \"pages/shop/index\"\n" +
                    "\t}, {\n" +
                    "\t\t\"type\": \"miniprogram\",\n" +
                    "\t\t\"name\": \"会员中心\",\n" +
                    "\t\t\"url\": \"http://mp.weixin.qq.com\",\n" +
                    "\t\t\"appid\": \"" + xcxAppId + "\",\n" +
                    "\t\t\"pagepath\": \"pages/user/index\"\n" +
                    "\t}]\n" +
                    "}";
            //JSONObject params1 = JSON.parseObject(body2);
            // String result2 = HttpUtils.sendPostJson(params1, url2);
            JSONObject params1 = JSON.parseObject(body);
            String result2 = HttpUtils.sendPostJson(params1, url2);
            //String strResult = HttpClientUtil.post(url2, body);
            //log.debug("微信调用：url = {}, params = {}, result = {}", url2, params1, strResult);
            log.debug("微信调用：url = {}, params = {}, result = {}", url2, params1, result2);
//            JSONObject resultJson2 = JSON.parseObject(result2);
//            String errcode2 = resultJson2.getString("errcode");
//            if (errcode2 != null && !"0".equals(errcode2)) {
//                log.debug("调用微信api返回值异常，错误码：{}", errcode2);
//                return Result.error("调用微信api返回值异常，错误码：" + errcode2 + "result：" + resultJson2);
//            }
        } catch (Exception e) {
            log.error("调用微信api发生异常", e);
            return Result.error("调用微信api发生异常");
        }
        return Result.OK("公众号菜单设置成功");


    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "店铺信息-查店铺额度")
    @ApiOperation(value = "店铺信息-查店铺额度", notes = "店铺信息-查店铺额度")
    @GetMapping(value = "/queryInfoById")
    public Result<?> queryStat(@RequestParam(name = "id", required = true) String id) {
        StoreInfo storeInfo = storeInfoService.getById(id);

        return Result.OK(storeInfo);
    }
}
